#!/usr/bin/env python

""" Example for analyse TLS malware by using JA3 fingerprints """

__author__ = "Luis Campo Giralte"
__copyright__ = "Copyright (C) 2013-2020 by Luis Campo Giralte"
__revision__ = "$Id$"
__version__ = "0.1"

import sys
import json
import re
sys.path.append("../src/")
import pyaiengine

fingerprints = dict()

class databaseAdaptor(pyaiengine.DatabaseAdaptor):

    def __init__(self):
        pass

    def update(self, key, data):
        d = json.loads(data)

        if (d["layer7"] == "ssl"):
            f = d["info"]["fingerprint"]
            if (f):
                print(json.dumps(json.loads(data), sort_keys=True,indent=4, separators=(',', ': ')))
                if f in fingerprints:
                    print("WARNING: Malware '%s' on '%s'" % (fingerprints[f], key))

    def insert(self, key):
        pass

    def remove(self, key):
        pass


def load_fingerprints():

    # The file has been download from https://sslbl.abuse.ch/blacklist/ja3_fingerprints.rules
    with open("ja3_fingerprints.rules") as f:
        for line in f.readlines():
            if (not line.startswith("#")):
                l = line.strip()
                a = re.split("\(msg:", l)
                # Parse the line
                name = a[1].split("\"")[1]
                value = a[1].split("content:")[1].split(";")[0].replace("\"","")
                fingerprints[value] = name

    return fingerprints

def callback_ssl(flow):

    d = flow.ssl_info
    if (d):
        f = d.fingerprint
        if f in fingerprints:
            malware_name = fingerprints[f] 
            print("WARNING: Malware '%s' on '%s'" % (malware_name, flow)) 
            flow.label = malware_name

if __name__ == '__main__':

    fingerprints = load_fingerprints()

    """ The detection is maded on the databaseAdaptor """
    db = databaseAdaptor()

    stack = pyaiengine.StackLan()
    dm = pyaiengine.DomainNameManager()
    dom = pyaiengine.DomainName("All .com", ".com")
    dom.callback = callback_ssl

    dm.add_domain_name(dom)

    """ The detection is maded on the SSL client hello """
    stack.set_domain_name_manager(dm, "SSLProtocol")

    source = "/home/luis/pcapfiles/malware/2018-09-06-Emotet-infection-with-IcedID-and-AZORult.pcap"

    stack.tcp_flows = 500000
    stack.udp_flows = 163840

    """ Depending on where you want to carrie out the detection you set the adaptor or not """
    stack.set_tcp_database_adaptor(db)

    with pyaiengine.PacketDispatcher(source) as pd:
        pd.stack = stack
        pd.run()

    stack.show_protocol_statistics()
    dm.show()
    sys.exit(0)

